using System.Collections.Generic;
using System.ComponentModel;
using System;
using Pegasus;
using System.Diagnostics;

namespace RollManager.Library.Utils
{
    public class ProgressReporter : List<string>
    {
        private BackgroundWorker worker = null;

        public ProgressReporter( BackgroundWorker worker ) : base() 
        {
            this.worker = worker;
        }

        public void Add( ServerAdvancement advancement )
        {
            if( worker == null )
            {
                Debug.WriteLine( string.Format( "Advanced to server {0}", advancement.Server ) );
            }
            else
            {
                worker.ReportProgress( 0, advancement );
            }
        }

        public void Add( Exception ex )
        {
            foreach( string str in ExceptionHelper.DumpExceptionAll( ex ).Split( new string[] { Environment.NewLine }, StringSplitOptions.None ) )
            {
                Add( str.Split( '\n' ) );
            }
        }

        public new void Add( string item )
        {
            base.Add( item );
            reportProgressIfNeeded();
        }

        public void Add( List<string> strs )
        {
            AddRange( strs.ToArray() );
        }

        public void Add( string[] strings )
        {
            AddRange( new List<string>( strings ) );
        }

        public void AddFormat( string str, params object[] args )
        {
            Add( string.Format( str, args ) );
        }

        public new void AddRange( IEnumerable<string> collection )
        {
            base.AddRange( collection );
            reportProgressIfNeeded();
        }

        public void ReportProgress()
        {
            if( worker == null )
            {
                foreach( string msg in ToArray() )
                {
                    Debug.WriteLine( string.Format( "Message: {0}", msg ) );
                }
            }
            else
            {
                worker.ReportProgress( 0, ToArray() );
            }

            Clear();
        }

        private void reportProgressIfNeeded()
        {
            if( Count > 0 )
            {
                ReportProgress();
            }
        }
    }
}